// pages/device.js
const ecUI = require("../../utils/ecUI.js");
const ecBLE = require("../../utils/ecBLE.js");

const {
  dec2hex,
  endianConv,
  hexCharCodeToStr,
  stringToHex,
  convertSecondsToHMS,
  hexStringToByteArray,
  dateFormat,
  formatTime,
  sleep
} = require("../../utils/util.js");

const { crc16 } = require("../../utils/crc-16.js");

const logEnable = true;

function log(...args) {
  if (logEnable) {
    console.log(...args);
  }
}

let ctx;
let isCheckScroll = true;
let isCheckRevHex = true;
let isCheckSendHex = true;
let sendData = "";

let focus = false;
let startTimeStamp = new Date().getTime();

let T1 = null;
let T2 = null;

const filemgr = wx.getFileSystemManager();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    count: 0,
    active: 'search',
    // active: "ota",
    recordTime: "",
    textRevData: [],
    scrollIntoView: "scroll-view-bottom",

    wid: "38070000",  // 写入ID
    rid: "48070000", // 读取 ID
    speed: "",
    voltage: "",
    ec: "",
    temp: "",
    motorState: "",
    othState: "",

    setSpeed: 0,
    setRun: 0,
    setPower: "19",

    // ota
    scrollIntoView2: "scroll-view-bottom3",
    isConnect: true,
    otaNowState: "", // connecting, connected, updating, update-success, update-fail, disconnecting, disconnected
    updataHex: null, //string格式的数据放这里
    totalCount: 0,
    curPkg: 0,
    percentage: 0,
    chooseFile: null,
    textOutRevData: "",
    // 1.连接成功
    // 2.版本信息
    // 3.握手成功
    // 4.升级成功
    // 5.版本信息
    steps: [
      {
         text: '页面加载成功',
      },
    ],
    stepActive: 1
  },
  onReady() {
    ctx = this;
   
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    // console.log(crc16('55CC00000238B00B190100000000')) // 7112
    // console.log(crc16('55AA000002480BB0800C0F4101FF')) // 92F3

    ctx = this;
    isCheckScroll = true;
    isCheckRevHex = true;
    isCheckSendHex = true;
    // sendData = ''
    // ecBLE.setChineseType(ecBLE.ECBLEChineseTypeGBK)
    ctx.setData({
      recordTime: new Date().getTime(),
      percentage: 100,
      step: [],
      stepIndex: 0
    });
    ecBLE.setChineseType(ecBLE.ECBLEChineseTypeUTF8);
  },
  onShow() {
    // wx.setStorageSync('localPwd', '12345678');
    ctx = this;
    focus = false;
    sendData = "";
    //on disconnect
    ecBLE.onBLEConnectionStateChange(ctx.bleStateChange);
    //receive data
    console.log("bleValueChange");
    ecBLE.onBLECharacteristicValueChange(ctx.bleValueChange);
  },
  bleStateChange() {
    ecUI.showModal("提示", "设备断开连接", () => {
      log("reLaunch");
      wx.reLaunch({
        url: "/pages/index/index",
      });
    });
  },
  bleValueChange(str, strHex) {
    console.log("strHex ===>", strHex);
    if (ctx.data.active === "search") {
      // console.log("search strHex", strHex);
      // console.log('Receive Data ===>', strHex, '\r\n')
      // if (ctx.data.recordTime) {
      // let data =
      //     ctx.data.textRevData +
      //     dateFormat('[hh:mm:ss,S]:', new Date()) +
      //     (isCheckRevHex ? strHex.replace(/[0-9a-fA-F]{2}/g, ' $&') : str) +
      //     '\r\n'
      // // console.log(data)
      // let temp = strHex.replace(/[0-9a-fA-F]{2}/g, " $&");
      // temp = temp.slice(6, -4);
      let tRec = strHex.slice(4, -4);
      tRec = tRec.replace(/[0-9a-fA-F]{2}/g, " $&");
      const arr = [
        dateFormat("[hh:mm:ss.S]", new Date()),
        tRec,
        new Date().getTime(),
      ];
      const textRevData = ctx.data.textRevData;
      textRevData.push(arr);
      ctx.setData({ textRevData });
      if (ctx.data.scrollIntoView === "scroll-view-bottom") {
        ctx.setData({ scrollIntoView: "scroll-view-bottom2" });
      } else {
        ctx.setData({ scrollIntoView: "scroll-view-bottom" });
      }
      // }

      let end = new Date().getTime();
      // const flag = (end - startTimeStamp) < 240
      const flag = end - startTimeStamp < 300;
      if (focus || flag) return;

      // mark

      //    const strHex = '55AA00000248B00B800C0F4101FF92F3'
      // 55AA480700000000042E0E2E00269C63
      // 48 07 00 00 00 00 04 C4 1D 3D 00 35 659A
      // 48 07 00 00 00 00 01 2C 1E 46 00 75 B
      const cmd = strHex.slice(0, 4);

      if (cmd === "55AA") {
        const sign = strHex.slice(-4);
        const dt = strHex.slice(0, -4);
        const sign_str = crc16(dt);
        // if (sign === sign_str) {
        // const id = strHex.slice(4, 12)
        const id = strHex.slice(4, 12);

        let speed = strHex.slice(12, 16);
        speed = parseInt(endianConv(speed), 16);

        let voltage = strHex.slice(16, 20);
        voltage = parseInt(endianConv(voltage), 16) / 10;

        let ec = strHex.slice(20, 22);
        ec = parseInt(ec, 16) / 10;

        let temp = strHex.slice(22, 24);
        temp = parseInt(temp, 16) - 40;

        let motorState = Number(strHex.slice(24, 26));

        let othState = strHex.slice(26, 28);
        othState = parseInt(othState, 16).toString(2);

        this.setData({
          speed,
          voltage,
          ec,
          temp,
          motorState,
          othState,
          // setRun: +othState[5],
          // setSpeed: speed
        });

        if (!T1) {
          T1 = setInterval(() => {
            this.setDeviceData();
          }, 1000);
        }
      }
    }
    if (ctx.data.active === "ota") {
      // console.log("ota strHex", strHex);
      // let textOutRevData =
      //   ctx.data.textOutRevData +
      //   // dateFormat("[hh:mm:ss,S]:", new Date()) +
      //   strHex.replace(/[0-9a-fA-F]{2}/g, " $&") +
      //   "\r\n";

      
      // ctx.setData({ textOutRevData });
      // if (ctx.data.scrollIntoView2 === "scroll-view-bottom3") {
      //   ctx.setData({ scrollIntoView2: "scroll-view-bottom4" });
      // } else {
      //   ctx.setData({ scrollIntoView2: "scroll-view-bottom3" });
      // }

      if (ctx.data.otaNowState === "connecting") {
        const isConnectHex = strHex.slice(12, -4);
        if (isConnectHex == "5533850203040000") {
          const step = []
          step.push({text: "连接成功"})
          ctx.setData({ otaNowState: "connected", isConnect: true, step, stepIndex: 0 });
        }
      }
      if (ctx.data.otaNowState === "updating") { 
        const state = strHex.slice(16, 18);
        // if (state == "84") {
            // if (ctx.data.curPkg < ctx.data.totalCount) {
            //     ctx.setData({
            //         curPkg: (ctx.data.curPkg + 1)
            //     }, () => {
            //         ctx.nextPkg(ctx.data.curPkg)
            //     })
            // } else {
            //     ecUI.showToast("升级文件传输成功");
            //     ctx.getVer()
            //     ctx.setData({ 
            //         otaNowState: 'connected',
            //         updataHex: null, //string格式的数据放这里
            //         totalCount: 0,
            //         curPkg: 0,
            //         percentage: 0,
            //         chooseFile: null,
            //     });
            //     // ctx.endPkg(ctx.data.curPkg)
            // }
            // const percentage = Math.floor((ctx.data.curPkg / ctx.data.totalCount) * 100)
            // ctx.setData({
            //     percentage,
            // })


        // } else {
        //     ecUI.showToast("升级文件传输失败，请重新连接");
        //     ctx.setData({ 
        //         isConnect: false, 
        //         otaNowState: '',
        //         updataHex: null, //string格式的数据放这里
        //         totalCount: 0,
        //         curPkg: 0,
        //         percentage: 0,
        //         chooseFile: null,
        //      });
        // }
      }
    }
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    ecBLE.onBLEConnectionStateChange(() => {});
    ecBLE.onBLECharacteristicValueChange(() => {});
    // ecBLE.closeBLEConnection();
    clearInterval(T1);
    T1 = null;
    clearInterval(T2);
    T2 = null;
  },
  onHide() {
    ecBLE.onBLEConnectionStateChange(() => {});
    ecBLE.onBLECharacteristicValueChange(() => {});
    clearInterval(T1);
    T1 = null;
    clearInterval(T2);
    T2 = null;
  },
  onChange(e) {
    const active = e.detail.name;
    this.setData({
      active,
        percentage: 0
    });
    clearInterval(T1);
    T1 = null;
  },
  record() {
    ctx = this;
    ctx.setData({
      recordTime: new Date().getTime(),
      count: 0
    },() => {
      clearInterval(T2);
      T2 = setInterval(() => { 
        ctx.setData({
          count: ctx.data.count + 1
        })
      }, 1000);
    });
  },
  setDeviceData() {
    // 55CC00000238 B00B1901000000007112
    let data = "55CC" + this.data.wid;
    let speed = this.data.setSpeed;
    console.log(speed);
    console.log(speed.toString(16));

    speed = endianConv(
      Number(speed).toString(16).padStart(4, "0")
    ).toUpperCase();
    data += speed;
    data += this.data.setPower;
    data += "0" + this.data.setRun;
    data += "00000000";
    data += crc16(data);
    sendData = data;
    this.btSendTap();
  },
  saveRecord() {
    clearInterval(T2);
    // C:\Users\Administrator\AppData\Local\微信开发者工具\User Data\c02561fbce29d89f3f7c746d76504a37\WeappSimulator\WeappFileSystem\o6zAJs2KZgYPwSoj4rg8jk4Qhg58\wxa11578cc57e42bc6\usr
    //    const  arr = [['张**', '李**', 'A',0,0,'C', '陈**', '何**'] , ['张**', '李**', 'A',0,0,'C', '陈**', '何**']]
    const textRevData = ctx.data.textRevData;
    const arr = textRevData.filter((i) => i[2] >= ctx.data.recordTime);
    const data = arr.join("\n");
    const fs = wx.getFileSystemManager();
    // console.log(`${wx.env.USER_DATA_PATH}/${formatTime(new Date())}.csv`)
    const filePath = `${wx.env.USER_DATA_PATH}/${formatTime(new Date())}.csv`;
    fs.writeFileSync(filePath, data, "utf8");
    wx.showModal({
      title: "提示",
      content: "保存成功",
      showCancel: true,
      cancelText: "取消",
      cancelColor: "#000000",
      confirmText: "打开文件",
      confirmColor: "#3CC51F",
      success: (result) => {
        if (result.confirm) {
          wx.openDocument({
            filePath,
            fileType: "xls",
            success: function (res) {},
          });
        }
      },
      fail: () => {},
      complete: () => {},
    });
  },
  btSendTap() {
    let data = sendData
      .replace(/\s*/g, "")
      .replace(/\n/g, "")
      .replace(/\r/g, "");
    if (data.length === 0) {
      ecUI.showModal("提示", "请输入要发送的数据");
      return;
    }
    if (data.length % 2 != 0) {
      ecUI.showModal("提示", "数据长度只能是双数");
      return;
    }
    if (data.length > 488) {
      ecUI.showModal("提示", "最多只能发送244字节");
      return;
    }
    if (!new RegExp("^[0-9a-fA-F]*$").test(data)) {
      ecUI.showModal("提示", "数据格式错误，只能是0-9,a-f,A-F");
      return;
    }
    console.log("Send Data====>", sendData + "\r\n");
    ecBLE.writeBLECharacteristicValue(data, true);
  },

  focusHandle() {
    focus = true;
  },
  blurHandle(e) {
    startTimeStamp = new Date().getTime();
    // const index = e.target.dataset.index
    // let hex = `0110040000020400${ctx.data.windSwitch}${ctx.data.windGear}${dec2hex(ctx.data[`windGearVal_${index}`]*10).padStart(4, '0')}`
    // const crc = CRC.ToModbusCRC16(hex, true);
    // hex += crc
    // sendData = hex
    // console.log('write::sendData:inputWindHandle', sendData)
    // ctx.btSendTap('write')
    focus = false;
  },
  changeHandle: (e) => {
    let value = e.detail;
    // const index = e.target.dataset.index
    // value=value.replace(/[^0-9.]/g, '').replace(/^\.+/g, '').replace(/(\.)(\d*)(\1*)/g, '$1$2').replace(/^(\-)*(\d+)\.(\d).*$/, '$1$2.$3')
    // if (+value<0) {
    //     value = 0
    // }
    // if (+value>100) {
    //     value = 100
    // }
    ctx.setData({
      setSpeed: value,
    });
  },
  runChange() {
    startTimeStamp = new Date().getTime();
    focus = false;
    ctx.setData({
      setRun: this.data.setRun ? 0 : 1,
    });
  },

  set_value(e) {
    const { key } = e.currentTarget.dataset;
    const value = e.detail;
    this.setData({
      [`${key}`]: value,
    });
  },
  async send_value(e) {
    // 010600010050D836
    const { key, hexcode, registercode, multiple } = e.currentTarget.dataset;
    let hex = this.data.MODBUS + hexcode + registercode + "000102";
    hex += dec2hex(this.data[key] * Number(multiple), 4);
    await this.hexArraySendHandler(hex);
  },

  // OTA 升级

  linkHandler() {
    let data = "55CC";
    data += this.data.wid;
    // data += "22AA0A0607080000";
    data += "22AA050607080000";
    data += crc16(data);
    sendData = data;
    this.btSendTap();
    this.setData({
      otaNowState: "connecting",
    });
  },
  chooseFileHandler() {
    wx.chooseMessageFile({
      type: "file",
      count: 1,
      extension: ["hex"],
      success(res) {
        console.log(res);
        ctx.setData({
          chooseFile: res.tempFiles[0],
        });
      },
      fail(res) {
        console.log(res);
      },
      complete(res) {
        console.log(res);
      },
    });
  },
  updateOta() {
      console.log(ctx.data.chooseFile, ctx.data.isConnect);

    if (!ctx.data.chooseFile) {
      ecUI.showToast("请选择升级文件");
      return;
    }
    if (!ctx.data.isConnect) {
      ecUI.showToast("请先连接设备");
      return;
    }
    const targetPath = wx.env.USER_DATA_PATH;
   
    try {
      //   const resFile = filemgr.readFileSync(targetPath + `/${ctx.data.fileName}`, 'hex')
      ctx.getVer()
      const resFile = filemgr.readFileSync(ctx.data.chooseFile.path, 'hex');
      // console.log(`resFile: `, resFile)
      // let rrdata = res.data
      let totalCount = Math.ceil(resFile.length / (256 * 2));
      ctx.setData(
        {
          updataHex: resFile, //string格式的数据放这里
          totalCount: totalCount,
          curPkg: 0,
          otaNowState: "updating"
        },
        () => {
          // console.log(crc32(hexCharCodeToStr(ctx.data.updataHex)).toString(16).toUpperCase())
          ctx.firstPkg()
          
        }
      );

    //   const resFileLen = endianConv(dec2hex(resFile.length / 2, 8));

    //   const fnArr = ctx.data.fileName.split("V");
    //   const v = extractNumbers(fnArr[fnArr.length - 1]);
    //   const str = v.map((ele) => dec2hex(ele, 2)).join("");
    //   const resFileName = endianConv(padHex(`${str}`, 16));

      // console.log('resFileLen', resFileLen)
      // console.log('resFileName', resFileName)

    //   const code = `B55B17AA${dec2hex(
    //     this.data.curPkg,
    //     4
    //   )}${resFileLen}${resFileName}`;
    //   const sign = checkEnd(
    //     `AA${dec2hex(this.data.curPkg, 4)}${resFileLen}${resFileName}`
    //   );
    //   const data = code + sign;
    //   log(`发送第1个分片 data ===> ${data}`);
        
    } catch (e) {
      console.log("升级失败", e);
      ecUI.showToast(e);
    }
  },
  firstPkg() { 
    const resFileASI = filemgr.readFileSync(ctx.data.chooseFile.path, 'ascii');
    const lines = resFileASI.split("\n");
    const line1 = lines[1];
    const line2 = lines[2];
    const line3 = lines[3];
    const line4 = lines[4];
    const addr1 = line1.substring(3, 7)
    const addr2 = line2.substring(3, 7)
    const addr3 = line3.substring(3, 7)
    const addr4 = line4.substring(3, 7)
    let code = "55CC";
    code += ctx.data.wid;
    code += '22AA040000010001';
    code += addr1;
    code += addr2;
    code += addr3;
    code += addr4;
    code += crc16(code);
    sendData = code;
    log(`共${ctx.data.totalCount}个分片，发送第0个分片 sendData ===> ${sendData}\r\n`);
    sleep(500)
    ecBLE.writeBLECharacteristicValue(sendData, true);

    const step = JSON.parse(JSON.stringify(ctx.data.step))
    step.push({
      text: '握手成功'
    })
    ctx.setData({
      step,
      stepIndex: step.length - 1
    })

    ctx.updatePer()
  },
  nextPkg(nextAddr) {
    // const curPkg = ctx.data.curPkg
    sleep(5)
    let dataPart;
    if (nextAddr !== ctx.data.totalCount) {
      dataPart = ctx.data.updataHex.slice(
        (nextAddr - 1) * 256 * 2,
        nextAddr * 256 * 2
      );
    } else {
      dataPart = ctx.data.updataHex.slice((nextAddr - 1) * 256 * 2);
    }

    // dataPart = padHex(dataPart, 128)
    // let dataLen = dataPart.length / 2;

    // const code = `B55B${padHex(dec2hex(dataLen + 1 + 2), 1)}AA${endianConv(
    //   dec2hex(nextAddr, 4)
    // )}${dataPart}`;
    // const sign = checkEnd(`AA${endianConv(dec2hex(nextAddr, 4))}${dataPart}`);
    // const data = code + sign;

    let data = "55CC";
    data += ctx.data.wid;
    data += '22AA040000010001';
    data += dataPart;
    data += crc16(data);
    data = data;

    log(`共${ctx.data.totalCount}个分片， 发送第${nextAddr}个分片 data ===> ${data}\r\n`);
    ecBLE.writeBLECharacteristicValue(data, true);
    ctx.updatePer()
 
  },
  updatePer() {
    if (ctx.data.curPkg < ctx.data.totalCount) {
        ctx.setData({
            curPkg: (ctx.data.curPkg + 1)
        }, () => {
            ctx.nextPkg(ctx.data.curPkg)
        })
    } else {
        ecUI.showToast("升级文件传输成功");
        sleep(500)
        ctx.getVer()
        ctx.setData({ 
            otaNowState: 'connected',
            updataHex: null, //string格式的数据放这里
            totalCount: 0,
            curPkg: 0,
            percentage: 0,
            chooseFile: null,
        });

        const step = JSON.parse(JSON.stringify(ctx.data.step))
        step.push({
          text: '升级成功'
        })
        ctx.setData({
          step,
          stepIndex: step.length - 1
        })
        // ctx.endPkg(ctx.data.curPkg)
    }
    const percentage = Math.floor((ctx.data.curPkg / ctx.data.totalCount) * 100)
    ctx.setData({
        percentage,
    })
  },

  endPkg() {
    const crc = endianConv(
      crc32(hexCharCodeToStr(ctx.data.updataHex)).toString(16).toUpperCase()
    );
    const code = `B55B07AAFFFF${crc}`;
    const sign = checkEnd(`AAFFFF${crc}`);
    const data = code + sign;
    log(`发送最后一个分片 data ===> ${data}`);
    ecBLE.writeBLECharacteristicValue(data, true);
  },
  getVer() {
        // const resFileASI = filemgr.readFileSync(ctx.data.chooseFile.path, 'ascii');
        // const lines = resFileASI.split("\n");
        // const line1 = lines[1];
        // const line2 = lines[2];
        // const addr1 = line1.substring(3, 7)
        // const addr2 = line2.substring(3, 7)
        // let getVerCmd = "55CC";
        // getVerCmd += ctx.data.id;
        // getVerCmd += '00000A';
        // getVerCmd += addr1;
        // getVerCmd += addr2;
        // getVerCmd += '00';

        let getVerCmd = "55CC";
        getVerCmd += ctx.data.wid;
        // 22AA050607080000
        getVerCmd += '22AA0A0607080000'
        getVerCmd += crc16(getVerCmd);
        sendData = getVerCmd;
        log(`获取版本信息 data ===> ${getVerCmd}`);
        ecBLE.writeBLECharacteristicValue(sendData, true);

        const step = JSON.parse(JSON.stringify(ctx.data.step))
        step.push({
          text: '读取版本成功'
        })
        ctx.setData({
          step,
          stepIndex: step.length - 1
        })
  },
});
